# coding=utf-8
"""
author: jamon
"""
import struct

from obespoir.share.encodeutil import AesEncoder


class MsgProtocol(object):
    """消息协议，包含消息处理"""

    def __init__(self):
        # (int, int, int)  -> (message_length, command_id, version)
        self.hand_fmt = "iii"
        self.head_len = struct.calcsize(self.hand_fmt)
        self.identifier = 0
        self.encode_ins = AesEncoder()
        self.version = 0

        self._buffer = b""    # 数据缓冲buffer
        self._head = None     # 消息头, [message_length, command_id, version]
        self.transport = None
        super().__init__()

    def pack(self, data: str, command_id: int):
        """
        打包消息， 用於傳輸
        :param data:  傳輸數據
        :param command_id:  消息ID
        :return: bytes
        """
        data = self.encode_ins.encode(data)
        length = data.__len__() + self.head_len
        head = struct.pack(self.hand_fmt, length, command_id, self.version)
        return head + data

    def unpack(self, pack_data):
        head_len = self.head_len    # noqa
        if head_len > len(pack_data):
            return None

        data_head = pack_data[0:head_len]
        list_head = struct.unpack(self.hand_fmt, data_head)
        data = pack_data[head_len:]
        result = self.encode_ins.decode(data)
        if not result:
            result = {}

        return {'result': True, 'command': list_head[1], 'data': result}
